window.onload = () => {
    const VSHADER_SOURCE = `
    attribute vec4 a_Position;
    attribute vec2 a_TexCoord;
    varying vec2 v_TexCoord;
    uniform mat4 u_ModelMatrix;
    void main(){
      gl_Position =u_ModelMatrix * a_Position;
      v_TexCoord = a_TexCoord;
    }`;

    const FSHADER_SOURCE = `
    precision mediump float;
    uniform sampler2D u_Sampler;
    varying vec2 v_TexCoord;
    void main(){
      gl_FragColor = texture2D(u_Sampler,v_TexCoord);
    }`;
    const canvas = document.getElementById('webgl');
    const gl = getWebGLContext(canvas);

    if (!gl) {
        console.log('Fail');
        return;
    }
    if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log('Failed');
        return;
    }

    let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
    let a_TexCoord = gl.getAttribLocation(gl.program, 'a_TexCoord');
    let u_ModelMatrix = gl.getUniformLocation(gl.program, 'u_ModelMatrix');

    if (a_Position < 0) {
        return;
    }
    let positonAndColor = [];
    canvas.addEventListener('click', e => {
        let [x, y] = [e.clientX, e.clientY];
        let rect = e.target.getBoundingClientRect();
        x = (x - rect.left) / (rect.width / 2) - 1;
        y = 1 - (y - rect.top) / (rect.height / 2);
        positonAndColor = [
            [x, y + 0.3, 0.0, 1.0,
                x, y, 0.0, 0.0,
                x + 0.3, y + 0.3, 1.0, 1.0,
                x + 0.3, y, 1.0, 0.0
            ],
            [Math.random(), Math.random(), Math.random(), Math.random()]
        ];
        let vertexSizeBuffer = gl.createBuffer();
        if (!vertexSizeBuffer) return;
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexSizeBuffer);
        let verticesSizes = new Float32Array(positonAndColor[0]);
        gl.bufferData(gl.ARRAY_BUFFER, verticesSizes, gl.STATIC_DRAW);
        let FSIZE = verticesSizes.BYTES_PER_ELEMENT;

        gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, FSIZE * 4, 0);
        gl.enableVertexAttribArray(a_Position);

        gl.vertexAttribPointer(a_TexCoord, 2, gl.FLOAT, false, FSIZE * 4, FSIZE * 2);
        gl.enableVertexAttribArray(a_TexCoord);

        let radian = 2 * Math.PI * Math.random();
        let cosB = Math.cos(radian);
        let sinB = Math.sin(radian);

        let currentAngle = 0.0;
        let currentTranslate = [0, 0, 0];
        const ANGLE_STEP = 180.0;
        const TRANSLATE_STEP = [(0.4 - x), -y, 0];
        let modelMatrix = new Matrix4();


        let g_last = Date.now();

        let texture = gl.createTexture();
        let u_Sampler = gl.getUniformLocation(gl.program, 'u_Sampler');


        const animateRotate = currentAngle => {
            let now = Date.now();
            let elapsed = now - g_last;
            g_last = now;
            let newAngle = currentAngle + (ANGLE_STEP * elapsed) / 1000.0;
            return newAngle % 360;
        };

        const animateTranslate = currentTranslate => {
            let now = Date.now();
            let elapsed = now - g_last;
            g_last = now;
            let newPosition = [currentTranslate[0] + (TRANSLATE_STEP[0] * elapsed) / 1000,
                currentTranslate[1] + (TRANSLATE_STEP[1] * elapsed) / 1000, currentTranslate[2] + 0
            ];
            return newPosition;
        };
        let image = new Image();
        image.src = './p2.png';
        image.onload = () => {
            gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, texture);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
            gl.uniform1i(u_Sampler, 0);

            const tick = () => {
                modelMatrix.setRotate(0, 1, 0, 0);
                requestAnimationFrame(tick);
                if (x + currentTranslate[0] > 0.410 || x + currentTranslate[0] < 0.390) {
                    currentTranslate = animateTranslate(currentTranslate);
                } else {
                    currentAngle = animateRotate(currentAngle);
                    modelMatrix.setRotate(currentAngle, 1, 0, 0);
                }
                modelMatrix.translate(...currentTranslate);
                gl.uniformMatrix4fv(u_ModelMatrix, false, modelMatrix.elements);
                gl.clear(gl.COLOR_BUFFER_BIT);
                // gl.drawArrays(gl.TRIANGLES, 0, 3);
                gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
            };

            tick();
        };

    });
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
};